package App.Filter;

import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.access.AccessDeniedHandler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

/**
 * Created by xw on 2018/11/16.
 */




//@Component
public class RestAccessDeniedHandler implements AccessDeniedHandler {

   // public static final Logger LOG = Logger.getLogger(RestAccessDeniedHandler.class);

    Logger _log = Logger.getLogger("RestAccessDeniedHandler");
    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException exc) throws IOException, ServletException {

       // Authentication auth = SecurityContextHolder.getContext().getAuthentication();


        _log.info("access deny error:luke");
        response.getWriter().print("You don't have required role to perform this action.");

       /* if (auth != null) {
            LOG.warn("User: " + auth.getName()
                    + " attempted to access the protected URL: "
                    + request.getRequestURI());
        }*/

       /* response.setStatus(HttpStatus.FORBIDDEN.value());

        Map<String, Object> data = new HashMap<>();
        data.put("timestamp2", new Date());
        data.put("status2",HttpStatus.FORBIDDEN.value());
        data.put("message2", "Access Denied");
        data.put("path2", request.getRequestURL().toString());

        OutputStream out = response.getOutputStream();
        com.fasterxml.jackson.databind.ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(out, data);
        out.flush();
*/

    //    response.sendRedirect(request.getContextPath() + "/accessDenied");
    }
}
